<template>
  <a-drawer
    title="添加用户"
    :width="780"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    :closable="false"
    @close="onClose"
  >
    <a-form :form="form" class="form" layout="vertical">
      <a-row class="form-row" :gutter="16">
        <a-col :lg="8" :md="12" :sm="24">
          <a-form-item style="display:none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item label="所属机构">
            <a-tree-select
              v-decorator="['deptId', {rules: [{ required: true, message: '请选择机构' }]}]"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeData"
              @focus="loadDept"
              placeholder="请选择机构"
              :replaceFields="replaceFields"
              :treeDefaultExpandAll="treeDefaultExpandAll"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :lg="8" :md="12" :sm="24">
          <a-form-item
            label="手机号">
            <a-input
              placeholder="请输入11位手机号"
              v-decorator="['phone']"/>
          </a-form-item>
        </a-col>
        <a-col :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item label="角色">
            <a-select
              mode="multiple"
              placeholder="请选择角色"
              @focus="loadRole"
              v-decorator="['roleIds',{rules: [{ required: true, message: '请选择角色'}]}]"
            >
              <a-select-option v-for="(action) in roleData" :key="action.id">
                {{ action.roleName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="8" :md="12" :sm="24">
          <a-form-item label="账户名称">
            <a-input
              placeholder="请输入全英文账户名称"
              v-decorator="['loginName',{rules: [{ required: true, message: '请输入账户名称', whitespace: true}, {pattern: /^[A-Za-z]+$/, message: '账户只能为英文'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item label="用户名称">
            <a-input
              placeholder="请输入中文用户名称"
              v-decorator="['userName',{rules: [{ required: true, message: '请输入用户名称', whitespace: true}, {pattern: /[\u4e00-\u9fa5]/, message: '用户名只能为中文'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="{span: 8}" :md="{span: 24}" :sm="24">
          <a-form-item label="性别">
            <a-select
              placeholder="请选择性别"
              v-decorator="['sex']" >
              <a-select-option value="0">男</a-select-option>
              <a-select-option value="1">女</a-select-option>
              <a-select-option value="2">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="警员编号">
            <a-input
              placeholder="请输入警员编号"
              v-decorator="['workNo', {rules: [{ required: true, message: '请输入警员编号', whitespace: true}]}]" />
          </a-form-item>
        </a-col>
        <a-col :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="邮箱">
            <a-input
              placeholder="请输入邮箱地址"
              v-decorator="['email']" />
          </a-form-item>
        </a-col>
        <a-col :lg="{span: 8}" :md="{span: 24}" :sm="24">
          <a-form-item label="状态">
            <a-select
              placeholder="请选择状态"
              v-decorator="['status', {rules: [{ required: true, message: '请输入选择状态', whitespace: true}]}]" >
              <a-select-option value="true">正常</a-select-option>
              <a-select-option value="false">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="备注">
            <a-textarea rows="4" placeholder="请输入备注" v-decorator="['remark']"></a-textarea>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-popconfirm title="真的放弃编辑吗?" @confirm="onClose">
        <a-button :style="{ marginRight: '8px' }">
          取消
        </a-button>
      </a-popconfirm>
      <a-button type="primary" @click="handleSubmit">
        保存
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
import { findAllDeptTree, findAllRole, addUser, editUser } from '@/api/system'
import { checkUserSuperAdmin } from '@/utils/permissions'
import pick from 'lodash.pick'

export default {
  name: 'UserModal',
  props: {
  },
  components: {
  },
  data () {
    return {
      replaceFields: {
        children: 'children',
        title: 'name',
        value: 'id'
      },
      treeData: [],
      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',
      visible: false,
      labelCol: {
        xs: { span: 10 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 10 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      deptCheck: true,
      spinning: false,
      treeDefaultExpandAll: false,
      form: this.$form.createForm(this),
      roleData: [],
      submitFlag: null,
      disabled: false
    }
  },
  beforeCreate () {
  },
  created () {
    // 如果为true,disabled不禁用
    this.disabled = !checkUserSuperAdmin()
  },
  methods: {
    onChange (value, label, extra) {
      this.form.resetFields(['deptId', 'roleIds'])
    },
    loadDept () {
      findAllDeptTree().then(res => {
        this.treeData = res.data
      })
    },
    loadRole () {
      findAllRole().then(res => {
        this.roleData = res.data
      })
    },
    add () {
      this.submitFlag = 'save'
      this.form.resetFields()
      this.mdl = {}
      // 如果禁用获取到当前登录人的租户,并且查询到该租户下面的部门和角色
      if (this.disabled) {
        this.loadRole()
        this.loadDept()
      } else {
        this.roleData = []
        this.treeData = []
      }
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'loginName', 'userName', 'phone', 'email', 'deptId', 'roleIds', 'sex', 'status', 'remark', 'workNo'))
      })
    },
    edit (record) {
      if (record.id > 0) {
        this.submitFlag = 'edit'
        this.loadRole()
        this.loadDept()
        this.mdl = Object.assign({}, record)
        this.mdl.roleIds = record.sysRoles.map(i => i.id)
        this.mdl.status = record.status.toString()
        this.spinning = true
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'id', 'loginName', 'userName', 'phone', 'email', 'deptId', 'roleIds', 'sex', 'status', 'remark', 'workNo'))
          this.spinning = false
        })
      }
    },
    onClose () {
      this.visible = false
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          // 判断标示,调用不同的接口
          if (this.submitFlag === 'save') {
            addUser(values).then(res => {
              if (res.code === 200) {
                this.$message.success('保存用户成功')
                this.$emit('ok')
                this.visible = false
              }
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            editUser(values).then(res => {
              if (res.code === 200) {
                this.$message.success('更新用户成功')
                this.$emit('ok')
                this.visible = false
              }
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        }
      })
    }
  },
  watch: {
  }
}
</script>
